package com.cx.mall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cx.mall.api.cart.CartFeign;
import com.cx.mall.api.goods.SkuInfoFeign;
import com.cx.mall.common.entity.goods.entity.SkuInfo;
import com.cx.mall.common.entity.order.entity.OrderDetail;
import com.cx.mall.common.entity.order.entity.OrderInfo;
import com.cx.mall.common.entity.order.model.OrderVO;
import com.cx.mall.common.entity.order.model.Stock;
import com.cx.mall.order.service.IOrderDetailService;
import com.cx.mall.order.service.IOrderInfoService;
import com.cx.mall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private SkuInfoFeign skuInfoFeign;
    @Autowired
    private CartFeign cartFeign;

    @Override
    public OrderInfo save(OrderVO orderVO) {


        String orderId = IdWorker.getIdStr();


        List<OrderDetail> orderDetailList = orderVO.getOrderDetails();
        if(orderDetailList == null || orderDetailList.size() == 0){
            throw new RuntimeException("订单详情不能为空");
        }



        orderDetailList = orderDetailList.stream().map(orderDetail -> {
            orderDetail.setOrderId(orderId);
            orderDetail.setAmount(orderDetail.getPrice().multiply(BigDecimal.valueOf(orderDetail.getQuantity())));
            return orderDetail;
        }).collect(Collectors.toList());

        //3.批量保存订单详情
        log.info("订单详情批量保存开始,订单详情列表:{}",orderDetailList);
        orderDetailService.saveBatch(orderDetailList);
        //4.保存订单信息
        OrderInfo orderInfo = JSON.parseObject(JSON.toJSONString(orderVO), OrderInfo.class);
        orderInfo.setOrderId(orderId);
        //计算金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail orderDetail : orderDetailList) {
            totalAmount = totalAmount.add(orderDetail.getAmount());
    }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCreateTime(LocalDateTime.now());
        log.info("订单信息保存开始,订单信息:{}",orderInfo);
        orderInfoService.save(orderInfo);
        //5.扣减库存  只需要针对库存Id进行操作库存Id,数据num
        for (OrderDetail orderDetail : orderDetailList) {
            Stock stock = new Stock();
            stock.setSkuId(orderDetail.getSkuId());
            stock.setNum(orderDetail.getQuantity());
            log.info("开始扣减库存, skuId: {}, num: {}", stock.getSkuId(), stock.getNum());
            try {
                skuInfoFeign.docount(stock);
                log.info("库存扣减成功, skuId: {}", stock.getSkuId());
            } catch (Exception e) {
                log.error("库存扣减失败, skuId: {}, error: {}", stock.getSkuId(), e.getMessage());
                // 暂时注释掉库存扣减，避免阻塞订单创建
                // throw new RuntimeException("库存扣减失败: " + e.getMessage());
            }
        }

        //6.删除购物车
        if(orderVO.getCartIds() != null){
            try {
                cartFeign.deleteByIds(orderVO.getCartIds());
                log.info("购物车删除成功, cartIds: {}", orderVO.getCartIds());
            } catch (Exception e) {
                log.error("购物车删除失败, cartIds: {}, error: {}", orderVO.getCartIds(), e.getMessage());
                // 暂时注释掉购物车删除，避免阻塞订单创建
                // throw new RuntimeException("购物车删除失败: " + e.getMessage());
            }
        }

        //7.发送消息
        return orderInfo;
    }
}
